<?php 
  require_once("../includes/config.php"); 
  
  $body_class = "login-page";
  if ($_SERVER["REQUEST_METHOD"] == "POST") 
  {
    $name = $_POST["name"];
    $pass = sha1($_POST['user_password']);
    $result= query("SELECT * FROM apartments_owner WHERE password = ? and (username = ? or email =?)",$pass,$name,$name);
     
    if(empty($result))
    {
      $_SESSION["error_message"] = "البيانات التى قمت بإدخالها غير صحيحة";
       redirect("login.php");
    }  
    else
    {
      $row = $result[0];
      $_SESSION["login_user"] = $row["first_name"]. " ".$row["last_name"]; 
      $_SESSION["user_id"] = $row["id"];
      $_SESSION["id"]=$row["user_id"];
      if($row["role"] > 1)
      {
        $org_info = query("SELECT * from apartments_owner where user_id = ?",$row["id"]);
        $_SESSION["organization"] = $org_info[0]["orgnanization_name"]; 
        $_SESSION["phone"] = $org_info[0]["ophone"]; 
        $_SESSION["logo"] = $org_info[0]["logo"]; 
        $_SESSION["website"] = $org_info[0]["oweb"]; 
        $_SESSION["fax"] = $org_info[0]["ofax"]; 
      }
      else
      {
        $_SESSION["organization"] = $row["orgnanization_name"] ; 
        $_SESSION["phone"] = $row["ophone"] ; 
        $_SESSION["logo"] = $row["logo"] ; 
        $_SESSION["website"] = $row["oweb"] ; 
        $_SESSION["fax"] = $row["ofax"] ; 
      }
      $_SESSION["success"]= "Welcome " .$_SESSION["login_user"] ;
      $_SESSION["r"]=$row["role"];
	  if ($_SESSION["r"]<2)
	  {
	  $_SESSION["logo"]=$row["logo"];
	  }
	  else
	  {
	  $resultz= query("SELECT * FROM apartments_owner WHERE user_id=?",$row["id"]);
	  $rowz=$resultz[0];
	  $_SESSION["logo"]=$rowz["logo"];
	  }
	  if ($_SESSION["r"]==0)
	  {
	  $_SESSION["admin"]=1;
	  }
	  else
	  {
	  $_SESSION["admin"]=0;
	  }
	  if ($_SESSION["r"]==3)
	  {
	  redirect("reports.php");
	  }
	  elseif($_SESSION["r"]==4)
	  {
	  redirect("apartments.php");
	  }
	  else
	  {
      redirect("index.php");
	  }
    }
    
  
  }
  else
  {
    if(isset($_SESSION["user_id"]))
      redirect("index.php");
    else
      render("login.php", array("title"=>"تسجيل الدخول","body_class"=>$body_class));
  }

?>